package com.usian.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.search.dto.UserSearchDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.search.feign.ApBehaviorEntryFeign;
import com.usian.search.service.ApUserSearchService;
import com.usian.search.service.ArticleSearchService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {


    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ApUserSearchService apUserSearchService;

    @Autowired
    private ThreadpoolTaskTest threadpoolTaskTest;

    @Autowired
    private ApBehaviorEntryFeign apBehaviorEntryFeign;

    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {

        if(dto == null || StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        //查询的时候调用记录搜索方法，该方法采用线程池获取异步保存

        ApUser user = AppThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        ApBehaviorEntry behaviorEntry = apBehaviorEntryFeign.findByUserIdOrEntryId(user.getId(), dto.getEquipmentId());
        if(behaviorEntry==null)
        {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户行为实体不存在");
        }
        apUserSearchService.insert(behaviorEntry.getEntryId(),dto.getSearchWords());

        threadpoolTaskTest.test();;

        //select * from table where (title=? or content=?) and publicTime< ?

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        SearchRequest searchRequest =new SearchRequest("app_info_article");
        SearchSourceBuilder searchSourceBuilder =new SearchSourceBuilder();

        QueryStringQueryBuilder stringQueryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").field("content")
                .defaultOperator(Operator.OR);

        boolQueryBuilder.must(stringQueryBuilder);

        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime());
        boolQueryBuilder.filter(rangeQueryBuilder);


        searchSourceBuilder.query(boolQueryBuilder);
        searchSourceBuilder.sort("publishTime", SortOrder.DESC);
        searchSourceBuilder.from(dto.getPageNum());
        searchSourceBuilder.size(dto.getPageSize());



        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);


        List<Map> result =new ArrayList<>();
        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();
        for(SearchHit hit : searchHits){
            String source = hit.getSourceAsString();
            Map map = JSON.parseObject(source, Map.class);
            result.add(map);
        }
        return ResponseResult.okResult(result);
    }
}
